<?php

class OrderController extends Controller
{
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    public function accessRules()
    {
        return array(
            array('allow',  // allow all users to perform 'index' and 'view' actions
                'actions'=>array('index'),
                'users'=>array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions'=>array('getpreorder','paidorder','getorders'),
                'users'=>array('@'),
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    }

	/**
	 * Declares class-based actions.
	 */
	public function actions() {
		return array(
		);
	}

    /**
     * 获得商品的订单填写信息
     *
     * @param $id 商品id
     */
    public function actionGetPreOrder($gid,$auctionid) {
        //lock order;
        $lockAuction = $this->lockAuction($gid,$auctionid);
        //商品信息
        $goods = $this->getGoodsBaseInfo($gid);
        $userid= CommonUtils::getUserId();
        $local = CommonUtils::getLocal();
        if ($local==_LOCAL_ZN) {
            $desc_field ='desc_zn';
            $name_field = 'name_zn';
        } else {
            $desc_field ='desc_en';
            $name_field = 'name_en';
        }

        if ($lockAuction['order']!=null) {
            $order = $lockAuction['order'];
        } else {
            $order = new Order();
            //地址信息
            $address = $this->getDefaultAddress($userid);
            if (!empty($address)) {
                $order->address = $address->address;
                $order->consignee = $address->consignee;
                $order->mobile = $address->mobile;
                $order->telephone = $address->telephone;
                $order->email= $address->email;
            } else {
                $order->address = "";
                $order->consignee = "";
                $order->mobile = "";
                $order->telephone = "";
                $order->email= "";
            }
            $order->goods = $gid;
            $order->distribution =_MESSAGE_DISTIBUTION;
            $order->freight = $goods->freight;
            $order->auction = $lockAuction['auctionid'];
            //售卖信息
            if (!empty($lockAuction['price'])) {
                $order->price = $lockAuction['price'];
                $order->sales = $lockAuction['salesid'];
            } else {
                $order->price = $goods->originPrice;
            }
            $order->userid = $userid;
            //订单号
            $order->createtime = time();
            $order->updatetime = time();
            $order->number = $this->getOrderNumber();
            $order->status = _ORDER_STATE_EDIT;
            $order->save(false);

            DubaiService::addOrderMonitorTask((string)$order->_id);
        }
        $result = $order->toArray();
        if (!empty($lockAuction['salesname'])) {
            $result['sales'] = $lockAuction['salesname'];
        } else {
            $result['sales'] = "";
        }
        $result['name'] = $goods->$name_field;
        $result['desc'] = $goods->$desc_field;
        $result['icon'] = $goods->icon;
        $result['grade'] = $this->getUser($userid)->grade;
        $result['orderid'] = (string)$order->_id;
        unset($result['_id']);
        unset($result['userid']);
        unset($result['status']);
        if ($lockAuction['order']==null) {
            //$b= DubaiService::addOrderMonitorTask((string)$order->_id);
            //if (empty($b) || !$b) {
             //   Yii::getLogger()->log("启动订单监控任务失败，请手动处理，订单Id=".(string)$order->_id);
           // }
        }
        echoToMobile($result);
     }

    /**
     * 支付订单
     */
    public function actionPaidOrder() {
        $userid = CommonUtils::getUserId();
        $order = $this->getOrder($_POST['orderid'],$userid);
        if(empty($order)||$order->status !=_ORDER_STATE_EDIT) {
            echoToError(_ERROR_ORDER_VERSION_INVALID,"需要登录");
        }
        //地址信息
        // $addressid = $_POST['addressid'];
        // $address = $this->getAddress($userid,$addressid);
        // if(empty($address)) {
        //     echoToError(_ERROR_ORDER_VERSION_INVALID,'地址无效，请确认后再试');
        // }
        $order->address = $_POST['address'];
        $order->consignee =$_POST['consignee'];
        $order->mobile = $_POST['mobile'];
        $order->telephone = $_POST['telephone'];
        $order->email= $_POST['email'];

        //售卖信息
        if (isset($_POST['message'])) {
            $order->message = $_POST['message'];
        }
        if (isset($_POST['grade'])) {
            $grade = $_POST['grade'];
        }
        if (!empty($grade) && $grade>0) {
            $order->paidprice = $order->price - $grade + $order->freight;
        } else {
            $order->paidprice = $order->price + $order->freight;
        }
        //订单号
        $order->status = _ORDER_STATE_PAID;
        try {
            $hasDecreaseGrade = false;
            $hasRecordLog = false;
            if (!empty($grade) && $grade>0) {
                //扣除积分
                $hasDecreaseGrade = $this->decreaseGrade($userid,$grade);
                //记录积分消费日志
                $userGradeLog = new UserGradeLog();
                $userGradeLog->userid = $userid;
                $userGradeLog->event = _GRADE_EVENT_DEDUCTION;
                $userGradeLog->grade =$grade;
                $hasRecordLog = $userGradeLog->save(flase);
            }
            $order->updatetime = time();
            $order->update();
        } catch(Exception $exception) {
            //事务还原
            if ($hasDecreaseGrade==true) {
                try {
                    $this->creaseGrade($userid,$grade);
                } catch(Exception $ex) {
                    //TODO 记录事务补偿日志
                }
            }
            if ($hasRecordLog==true) {
                try {
                    $userGradeLog->delete();
                } catch(Exception $ex) {
                    //TODO 记录事务补偿日志
                }
            }
        }
        echoToMobile("ok");
    }

    /**
     * 获得订单
     * @param int $status
     */
    public function actionGetOrders($status=0) {
        $userid = CommonUtils::getUserId();
        $local = CommonUtils::getLocal();

        if ($local==_LOCAL_ZN) {
            $desc_field ='desc_zn';
            $name_field = 'name_zn';
        } else {
            $desc_field ='desc_en';
            $name_field = 'name_en';
        }
        $resultArr = array();
        if ((int)$status!=0) {
            $query = array(
                'conditions' => array('status'=>array('=='=>(int)$status),'userid'=>array('=='=>$userid)),
                'select' => array('_id','status','sales','goods','freight','paidprice'),
                'limit' => _LIMITED_PAGE_SIZE,
                'sort' => array('updatetime'=>EMongoCriteria::SORT_DESC),
            );
        } else {
            $query = array(
                'conditions' => array('userid'=>array('=='=>$userid)),
                'select' => array('_id','status','sales','goods','freight','paidprice'),
                'limit' => _LIMITED_PAGE_SIZE,
                'sort' => array('updatetime'=>EMongoCriteria::SORT_DESC),
            );
        }
        $orders =Order::model()->findAll($query);
        if (!empty($orders)) {
            $len = count($orders);
            for($index=0;$index<$len;$index++) {
                $item = array();
                $goods = $this->getGoodsBaseInfo($orders[$index]->goods);
                $item['orderid'] = (string)$orders[$index]->_id;
                $item['status']=$orders[$index]->status;
                $item['price'] =$orders[$index]->paidprice;
                $item['name'] =$goods->$name_field;
                $item['desc'] =$goods->$desc_field;
                $item['icon'] = $goods->icon;
                $item['goods'] = (string)$goods->_id;
                if (!empty($orders[$index]->sales)) {
                    $item['sales'] = (string)$this->getSales($orders[$index]->sales)->_id;
                } else {
                    $item['sales'] = "";
                }
                array_push($resultArr,$item);
            }
        }
        echoToMobile($resultArr);
    }

    /**
     * 锁定，并返回获得商品的卖家信息及卖家报价。
     *
     * @param $id
     */
    private function lockAuction($gid,$auctionid) {
        $goodsAuction = $this->getGoodsAuction($auctionid);
        if (empty($goodsAuction)||$goodsAuction->goods!=$gid) {
            echoToError(_ERROR_SYSTEM_FAULT,"传入的数据非法！！！");
        }
        if ($goodsAuction->state != _GOODS_AUCTION_STATE_PROCESS) {
            echoToError(_ERROR_GOODS_VERSION_INVALID,"数据已过期请刷新后再试。");
        } else {
            $order = $this->getValidOrderByAuctionid($auctionid);
            $lock = (int)Yii::app()->redis->MSETNX(array(_REDIS_HASHKEY_GOODS_LOCK.$gid=>"1"));
            //成功
            if ($lock == 1){
                if ($order!=null) {
                    RedisCacheUtil::unlock($gid);
                    echoToError(_ERROR_ORDER_VERSION_INVALID,"商品售卖信息已过期，请刷新后再试。");
                } else {
                    Yii::app()->redis->EXPIRE(_REDIS_HASHKEY_GOODS_LOCK.$gid,_LOCK_EXPIRE_TIME);
                    //启动该订单监控程序。
                    $goodsAuction->locktime=time();
                    $goodsAuction->update();
                    //设置返回值
                    $result = array();
                    $salesid = $goodsAuction->sales;
                    if (!empty($salesid)) {
                        $sales =$this->getSales($salesid);
                        $result['salesname'] = $sales->nickname;
                        $result['salesid'] = $salesid;
                    } else {
                        $result['salesname'] ="'";
                        $result['salesid'] = null;
                    }
                    $result['price'] = $goodsAuction->lowprice;
                    $result['auctionid']=(string)$goodsAuction->_id;
                    $result['order'] = null;
                }
            } else {
                if (!empty($order) && $order->status==_ORDER_STATE_EDIT && $order->userid==CommonUtils::getUserId()) {
                    $salesid = $order->sales;
                    $sales =$this->getSales($salesid);
                    $result['salesname'] = $sales->nickname;
                    $result['salesid'] = $salesid;
                    $result['price'] = $goodsAuction->lowprice;
                    $result['auctionid']=(string)$goodsAuction->_id;
                    $result['order'] = $order;
                    return $result;
                }
                if (!empty($order) && $order->userid!=CommonUtils::getUserId()) {
                    $expipe1 = (int)Yii::app()->redis->TTL(_REDIS_HASHKEY_GOODS_LOCK.$gid);
                    echoToError(_ERROR_GOODS_LOCK,'该商品正等待其他买家付款，请'.$expipe1.'秒后再试。');
                }
                //解锁，需要记日志分析该状况是如何出现
                //TODO
                RedisCacheUtil::unlock($gid);
                echoToError(_ERROR_GOODS_VERSION_INVALID,"商品售卖信息已过期请刷新后再试。");
            }
        }
        return $result;
    }

    /**
     * 扣除积分并记录日志
     *
     * @param $userid
     * @param $cgrade
     */
    private function decreaseGrade($userid,$cgrade) {
        //积分异常
        $user = $this->getUser($userid);
        $user->grade = $user->grade - $cgrade;
        if ($user->grade<0) echoToError(_ERROR_ORDER_VERSION_INVALID,"积分不足以支付");
        return $user->update();
    }

    /**
     * 扣除积分并记录日志
     *
     * @param $userid
     * @param $cgrade
     */
    private function creaseGrade($userid,$cgrade) {
        $user = $this->getUser($userid);
        $user->grade = $user->grade + $cgrade;
        return $user->update();
    }

    /**
     * 得到商品基础信息
     *
     * @param $id
     */
    private function getGoodsBaseInfo($gid) {
        $local = CommonUtils::getLocal();

        if ($local==_LOCAL_ZN) {
            $desc_field ='desc_zn';
            $name_field = 'name_zn';
        } else {
            $desc_field ='desc_en';
            $name_field = 'name_en';
        }
        $mongoid = new MongoId($gid);
        $query = array(
            'conditions' => array('_id'=>array('=='=>$mongoid)),
            'select'=>array($name_field,$desc_field,'freight','icon','images','originPrice','_id'),
        );
        return Goods::model()->find($query);
    }

    /**
     * 得到订单
     * @param $orderid
     * @param $userid
     * @return EMongoDocument
     */
    private function getOrder($orderid,$userid=null) {
        $mongoid = new MongoId($orderid);
        if ($userid!=null) {
            $query = array(
                'conditions' => array('_id'=>array('=='=>$mongoid),'userid'=>array('=='=>$userid)),
            );
        } else {
            $query = array(
                'conditions' => array('_id'=>array('=='=>$mongoid),),
            );
        }
        return Order::model()->find($query);
    }

    /**
     * 获得用户信息
     * @param $userid
     * @return EMongoDocument
     */
    function getUser($userid) {
        $mongoid = new MongoId($userid);
        $query = array(
            'conditions' => array('_id'=>array('=='=>$mongoid)),
        );
        return UserInfo::model()->find($query);
    }

    /**
     * 获得地址信息
     * @param $userid
     * @param $addressId
     * @return EMongoDocument
     */
    private function getAddress($userid,$addressId) {
        $query = array(
            'conditions' => array('_id'=>array('=='=>new MongoId($addressId)),'userid'=>array('=='=>$userid)),
        );
        return UserAddress::model()->find($query);
    }

    /**
     * 获得地址信息
     * @param $userid
     * @param $addressId
     * @return EMongoDocument
     */
    private function getDefaultAddress($userid) {

        $uquery = array(
            'conditions' => array('_id'=>array('=='=>new MongoId($userid)),),
        );
        $user = UserInfo::model()->find($uquery);
        $query = array(
            'conditions' => array('_id'=>array('=='=>new MongoId($user->defaultAddress)),),
        );
        return UserAddress::model()->find($query);
    }

    /**
     * 获得订单号
     */
    private function getOrderNumber() {
        return time();
    }

    /**
     * 获得sales信息
     *
     * @param $salesId
     */
    private function getSales($salesId) {
        return Sales::model()->find(array('conditions'=>array('_id'=>array('=='=>new MongoId($salesId)))));
    }


    /**
     * 得到正在竞拍的商品竞拍信息
     * @param $id
     */
    private function getGoodsAuction($auctionid) {
        $query = array(
            'conditions' => array('_id'=>array('=='=>new MongoId($auctionid)))
        );
        return GoodsAuctioninfo::model()->find($query);
    }


    /**
     * 得到有效订单
     * @param $auctionid
     * @return EMongoDocument
     */
    private function getValidOrderByAuctionid($auctionid) {
        $query = array(
            'conditions' => array('auction'=>array('=='=>$auctionid),'status'=>array('!='=>_ORDER_STATE_CANCEL)),
        );
        return Order::model()->find($query);
    }
}